package com.kiki.stater;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * <p>
 * 测试生成代码
 * </p>
 *
 * @author K神
 * @date 2017/12/18
 * @see <a href="http://mp.baomidou.com/#/generate-code">generate-code</a>
 */
@SpringBootTest
public class CodeGenerator {
    @Test
    public void test(){
//        TypeTable a = new TypeTable();
    }


    @Test
    public void generateCode() {

        String packageName = "reader.tadu.modules.system";
        boolean serviceNameStartWithI = true;//user -> UserService, 设置成true: user -> IUserService
        String testTableNames[] = {"user"};
        //String tableNames[] = {"authors","book_channel","book_ios_rank","book_parts_api","book_rank","book_rank_xh","books","books_info","copyright_batch","copyright_book","copyright_type","platform_group_book","tag_book"};
        //String tableNames[] = {"book_img_size"};
        //String tableNames[] = {"book_img"};
        //String tableNames[] = {"book_charge"};
        //String tableNames[] = {"yz_book"};
        //String tableNames[] = {"tag"};
        //String tableNames[] = {"tag_categories"};
        //String tableNames[] = {"book_categories"};
//        String tableNames[] = {"cif_success"};
        //String tableNames[] = {"auth_user","auth_group_interface","auth_permission_interface","auth_user_groups_interface","auth_group_permissions_interface"};
//        String tableNames[] = {"book_parts"};
        String tableNames[] = {"sys_dept",
                "sys_dict",
                "sys_dict_detail",
                "sys_log",
                "sys_menu",
                "sys_role",
                "sys_user"};
        generateByTables(serviceNameStartWithI, packageName, tableNames);
    }

    private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
        AutoGenerator autoGenerator = new AutoGenerator();

        // 自定义模板配置，可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改，
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置，也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setController(null);
        tc.setEntity(null);
        tc.setMapper(null);
//        tc.setXml(null);
        tc.setService(null);
        tc.setServiceImpl(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        autoGenerator.setTemplate(tc);

        // 全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(false) // 不需要ActiveRecord特性的请改为false
                .setAuthor("李守青")
                .setOutputDir("G:\\code")
                .setFileOverride(true)
                .setEnableCache(false)    // XML 二级缓存
                .setBaseResultMap(true)  // XML ResultMap
                .setBaseColumnList(false); // XML columList

        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }

        //数据源配置
        String dbUrl = "jdbc:mysql://localhost:3306/tadu-cms?serverTimezone=UTC";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername("root")
                .setPassword("")
                .setDriverName("com.mysql.cj.jdbc.Driver");

        //策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(true)
                .setEntitySerialVersionUID(false)
                .setEntityTableFieldAnnotationEnable(false)
//                .setTablePrefix(new String[] { "tlog_", "tsys_" })// 此处可以修改为您的表前缀
                .setNaming(NamingStrategy.underline_to_camel) // 表名生成策略
                .setInclude(tableNames)//修改替换成你需要的表名，多个表名传数组
//                .setExclude(new String[]{"test"}) // 排除生成的表
//                .setSuperEntityClass("com.baomidou.demo.TestEntity")// 自定义实体父类
//                .setSuperEntityColumns(new String[] { "test_id", "age" }) // 自定义实体，公共字段
                .setSuperMapperClass("reader.tadu.base.TaduBaseMapper") // 自定义 mapper 父类
                .setSuperServiceClass("reader.tadu.base.ITaduService") // 自定义 service 父类
                .setSuperServiceImplClass("reader.tadu.base.TaduServiceImpl") // 自定义 service 实现类父类
//                .setSuperControllerClass("com.baomidou.demo.TestController") // 自定义 controller 父类
//                .setEntityColumnConstant(true)// 【实体】是否生成字段常量（默认 false）
//                .setEntityBuilderModel(true);  // 【实体】是否为构建者模型（默认 false）
                .setRestControllerStyle(true)
                  ;
        // 包配置
        PackageConfig packageConfig = new PackageConfig()
                .setParent(packageName)
                .setController("rest")
                .setEntity("entity");

        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
//        InjectionConfig customConfig = new InjectionConfig() {
//            @Override
//            public void initMap() {
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
//                this.setMap(map);
//            }
//        };
        // 自定义 xxList.jsp 生成
//        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//        focList.add(new FileOutConfig("/template.java.vm") {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                String expand = "/Users/lishouqing/codeGen3" + "/" + "expand";
//                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getControllerName());
//                return entityFile;
//            }
//        });
//        customConfig.setFileOutConfigList(focList);
//        autoGenerator.setCfg(customConfig);

        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine())// // 选择 freemarker 引擎，默认 Veloctiy
                .setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .execute();
    }
}

